<template>
  <div class="page-container">
    <div class="page-row">
      <el-card shadow="hover" style="flex:auto;margin-right:10px;" :body-style="{ padding: `20px 11px 11px` }">
        <el-row align="middle">
          <div style="margin-right:10px">
            <div class="tips-data">
              <span class="tips">供应商阶段</span>
            </div>
            <div class="tips-data">
              <span class="tips small-tips">数量</span>
            </div>
          </div>
          <el-row style="flex:1;">
            <div class="tips-cell" v-for="(item, index) in stage" :key="item.value">
              <div class="tips-item">
                <span :class="['tips-name', item.id < 0 ? 'red' : '']">{{ item.name }}</span>
                <el-icon v-if="index < stage.length - 2">
                  <ele-DArrowRight/>
                </el-icon>
              </div>
              <!-- 当前数据 -->
              <p :class="['item-data text-red', index < stage.length - 1 ? 'item-right' : '']">{{ item.count }}</p>
            </div>
          </el-row>
        </el-row>
      </el-card>
      <el-card shadow="hover" style="width: 500px" :body-style="{ padding: `8px 0 0` }">
        <el-row justify="space-between" style="padding: 0 11px">
          <h4>供应商数据总览</h4>
          <!--          <el-button type="primary" link size="small">查看详情</el-button>-->
        </el-row>
        <el-table size="small" :data="accountList" border style="margin-top:10px">
          <el-table-column label="累计成交供应数量" align="center" prop="dealAccount"></el-table-column>
          <el-table-column label="采购单总量" align="center" prop="procureAccount"></el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-row style="margin: 10px 0" justify="space-between">
      <el-row>
        <el-button size="small" type="primary" :icon="Plus" @click="dialogCreate = true">新建</el-button>
        <el-button size="small" type="warning" @click="checkAll">全部数据</el-button>
      </el-row>
      <el-row>
        <el-button type="default" size="small" @click="exportVisible = true">批量导出</el-button>
      </el-row>
    </el-row>

    <div class="table-box">
      <el-table size="small" :data="tableData" class="tableList" :summary-method="getStatistics" show-summary>
        <el-table-column type="selection" width="30" fixed="left"></el-table-column>
        <el-table-column v-for="item in header" :key="item.id" :prop="item.label"
                         :min-width="item.name.length > 4 ? `130px` : `90px`" align="center">
          <template #header>
            <span style="margin-right:2px;">{{ item.name }}</span>
            <!-- 可搜索表头 -->
            <el-popover placement="bottom" :width="100" trigger="click" v-if="item.isFilter && item.filter == 'search'">
              <template #reference>
                <el-icon :size="15" color="var(--el-color-primary)">
                  <ele-Search/>
                </el-icon>
              </template>
              <el-input :placeholder="`请输入${item.name}`" v-model.trim="search[item.label]" size="small" title="按下回车即可搜索"
                        clearable @input="getList">
              </el-input>
            </el-popover>
            <!-- 可筛选表头 -->
            <el-popover placement="bottom" :width="60" trigger="click" @change="getList" v-if="item.isFilter && item.filter == 'filter'">
              <template #reference>
                <el-icon :size="15" color="var(--el-color-primary)">
                  <ele-Filter/>
                </el-icon>
              </template>
              <el-scrollbar max-height="600px">
                <el-radio-group v-model="search[item.label]" size="small" v-if="filterData[item.label] && filterData[item.label].length > 0">
                  <el-radio v-for="radio in filterData[item.label]" :key="radio.name" :label="radio.name"
                            @click.prevent="onRadioChange(radio.value, item.label)">{{ radio.name }}
                  </el-radio>
                </el-radio-group>
                <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50" description="无数据"/>
              </el-scrollbar>
            </el-popover>
          </template>
          <template v-slot="{row}" v-if="item.label === 'shortName'">
            <span class="primary" @click="openDetail(row)">{{ row.shortName }}</span>
          </template>
          <template v-slot="{row}" v-else-if="item.isFilter && item.filter == 'filter'">
            <div v-for="dict in filterData[item.label]" v-show="dict.value == row[item.label]">{{ dict.name }}</div>
          </template>
          <template v-slot="{row}" v-else-if="item.label === 'mainContact'">
            <span>{{ row.mainContact.name }}</span>
          </template>
          <template v-slot="{row}" v-else-if="item.label === 'phone'">
            <span>{{ row.mainContact.phone }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180px" align="center">
          <template #default="{row}">
            <!--            scope.$index-->
            <el-button size="small" type="primary" link @click="payment(row)">付款</el-button>
            <el-button size="small" type="primary" link @click="refund(row)">退款</el-button>
            <el-button size="small" type="primary" link @click="invoice(row)">发票</el-button>
            <el-button size="small" type="primary" link @click="deleteSupplier(row)">删除</el-button>
            <el-button size="small" type="primary" link @click="modifyBlock(row, false)" v-if="row.blockState">解除屏蔽</el-button>
            <el-button size="small" type="primary" link @click="modifyBlock(row, true)" v-else>屏蔽消息</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-block">
      <el-pagination v-model:currentPage="search.current" v-model:page-size="search.size" :page-sizes="[10, 20, 30, 40]"
                     :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
                     :total="total" :hide-on-single-page="true" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>

    <!--    导出Excel表格-->
    <el-dialog v-model="exportVisible" title="导出Excel表格" destroy-on-close width="40%">
      <div class="mb-2 flex items-center text-sm">
        <el-radio-group v-model="isExportAll" class="ml-4" justify="space-around">
          <el-radio label="0" size="large">当前页面</el-radio>
          <el-radio label="1" size="large">所有数据</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="exportVisible = false">关闭</el-button>
            <el-button size="small" type="primary" :icon="Check" @click="batchExport">导出</el-button>
          </span>
      </template>
    </el-dialog>

    <!-- 新建供应商 -->
    <supplier-create v-model:dialogDrawer="dialogCreate" :isEdit="false" :SupplierSource="filterData.source" @onSubmit="checkAll"/>
    <!-- 供应商详情 -->
    <SupplierDetail v-model:dialogDrawer="dialogDetail" :form="detailData" :SupplierSource="filterData.source" :SupplierStage="filterData.stage" @onSubmit="getList"/>
  </div>
</template>

<script>
import {onMounted, reactive, toRefs} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Check} from '@element-plus/icons-vue'
import SupplierCreate from '../components/SupplierCreate.vue'
import SupplierDetail from '../components/SupplierDetail.vue'
import supplierApi from '/@/api/supplier/index'
import {getDictByCodes} from '/@/api/sys/dict'
import {Session} from "../../../utils/storage";

export default {
  name: 'Supplier',
  components: {
    SupplierCreate,
    SupplierDetail
  },
  setup() {
    const state = reactive({
      search: {
        current: 1,
        size: 10,
        shortName: null,
        productName: null,
        stage: null
      },
      dialogCreate: false,
      dialogDetail: false,
      detailData: {},
      isExportAll: '0',
      tableData: [],
      exportVisible: false,
      accountList: [{
        dealAccount: 0,
        procureAccount: 0
      }],
      filterData: {
        stage: [],
        source: []
      },
      dictMap: {},
      total: 0,
      stage: [
        {
          count: 0,
          name: '线索',
          value: '0'
        },
        {
          count: 0,
          name: '沟通需求',
          value: '1'
        },
        {
          count: 0,
          name: '报价',
          value: '2'
        },
        {
          count: 0,
          name: '合同订单',
          value: '3'
        },
        {
          count: 0,
          name: '终止',
          value: '4'
        }
      ],
      header: [
        {
          name: '服务商简称',
          isFilter: true,
          filter: 'search',
          label: 'shortName'
        }, {
          name: '供应产品',
          isFilter: true,
          filter: 'search',
          label: 'productName'
        }, {
          name: '采购金额',
          isFilter: false,
          filter: 'filter',
          label: 'amount'
        }, {
          name: '已付',
          isFilter: false,
          filter: 'filter',
          label: 'payAmount'
        }, {
          name: '应付',
          isFilter: false,
          filter: 'filter',
          label: 'debt'
        }, {
          name: '主要联系人',
          isFilter: false,
          filter: 'filter',
          label: 'mainContact'
        }, {
          name: '联系方式',
          isFilter: false,
          filter: 'filter',
          label: 'phone'
        }, {
          name: '阶段',
          isFilter: true,
          filter: 'filter',
          label: 'stage'
        }, {
          name: '来源',
          isFilter: true,
          filter: 'filter',
          label: 'source'
        }],
      summaryPay: '0.00',   // 表尾合计已付
      summaryDebt: '0.00'   // 表尾合计未付
    })

    const getList = () => {
      supplierApi.getSupplierPage(state.search).then(res => {
        state.tableData = res.data.records
        state.total = res.data.total
      }).catch(e => console.log(e))
    }
    // 查看所有
    const checkAll = () => {
      state.search = {
        current: state.search.current,
        size: state.search.size,
        shortName: null,
        productName: null,
        stage: null
      }
      getList()
    }
    const getStatistics = () => {
      return ['', '统计（全部）', '', '', state.summaryPay, state.summaryDebt]
    }
    // 导出
    const batchExport = () => {
      let p = state.search
      let params = Object.keys(p).map(key => key + '=' + encodeURIComponent(p[key])).join('&')
      supplierApi.export(params + '&isExportAll=' + state.isExportAll + '&17work=' + Session.get('token')).then(res => {
        downloadExcel(res)
      }).catch(e => ElMessage.error('导出失败!',e))
      state.exportVisible = false
    }
    // 删除
    const deleteSupplier = (row) => {
      ElMessageBox.confirm('确定删除供应商: ' + row.shortName + ' ？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        supplierApi.delete({id: row.id}).then(res => {
          if (res.data) {
            if (row.state != -1) {
              state.summaryPay = (state.summaryPay - row.payAmount).toFixed(2)
              state.summaryDebt = (state.summaryDebt - row.debt).toFixed(2)
            }
            getList()
            ElMessage.success('删除成功！')
          }
        }).catch(e => console.log(e))
      }).catch(err => {
      })
    }
    const onRadioChange = (val, name) => {
      // 重复点击同个值取消选中
      state.search[name] = state.search[name] == val ? null : val
      getList()
    }
    const payment = (row) => {

    }
    const refund = (row) => {

    }
    const invoice = (row) => {

    }
    const modifyBlock = (row, state) => {
      supplierApi.editBlock({id: row.id, blockState: state}).then(res => {
        if (res.data) {
          row.blockState = state
          ElMessage.success('修改成功！')
        }
      }).catch(e => console.log(e))
    }
    // 条数切换
    const handleSizeChange = e => {
      state.search.size = e
      handleCurrentChange(1)
    }
    // 页码切换
    const handleCurrentChange = e => {
      state.search.current = e
      getList()
    }
    // 打开供应商详情页
    const openDetail = (row) => {
      state.detailData = JSON.parse(JSON.stringify(row))
      state.dialogDetail = true
    }
    //该方法能否抽出没试过 但应该是不可以的
    const downloadExcel = (res) => {
      if (!res.data) {
        return;
      }
      const fileName = res.headers["content-disposition"].split("=")[1];
      const blob = new Blob([res.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      });
      const url = window.URL.createObjectURL(blob);
      const aLink = document.createElement("a");
      aLink.style.display = "none";
      aLink.href = url;
      aLink.setAttribute("download", decodeURI(fileName));
      document.body.appendChild(aLink);
      aLink.click();
      document.body.removeChild(aLink);
      window.URL.revokeObjectURL(url);
    }

    onMounted(() => {
      // 表格合计数据
      supplierApi.getSumAmount().then(res => {
        state.summaryPay = res.data.payAmount || '0.00'
        state.summaryDebt = res.data.debt || '0.00'
      }).catch(e => console.log(e))
      // 先加载完字典再请求分页, 表格数据渲染需要字典数据
      getDictByCodes(['SupplierStage', 'SupplierSource']).then(res => {
        state.filterData.stage = res.data['SupplierStage']
        state.filterData.source = res.data['SupplierSource']
        state.dictMap = res.data
        getList()
      }).catch(e => console.log(e))
      //获取供应商阶段统计
      supplierApi.getStageData().then(res => state.stage.forEach(item => item.count = res.data[item.value] || 0)).catch(e => console.log(e))
      supplierApi.getDataOverview().then(res => {
        state.accountList[0].procureAccount = res.data.procureAccount
        state.accountList[0].dealAccount = res.data.dealAccount
      })
    })

    return {
      Plus,
      Check,
      ...toRefs(state),
      refund,
      getList,
      invoice,
      payment,
      checkAll,
      openDetail,
      batchExport,
      modifyBlock,
      getStatistics,
      onRadioChange,
      deleteSupplier,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .page-row {
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;

    .tips-data {
      display: flex;
      align-items: center;
      height: 28px;
      margin-top: 20px;

      .tips {
        margin-right: 3px;
        font-size: 13px;
      }

      &:first-child {
        height: unset;
        margin-top: 0;
      }
    }

    .tips-cell {
      flex: auto;

      .tips-item {
        display: flex;
        align-items: center;
        padding-left: 10px;
        justify-content: space-between;
      }

      .tips-name {
        margin-right: 10px;
        flex: 1;
        overflow: hidden;
        text-align: center;
      }

      .item-data {
        text-align: center;
        height: 28px;
        margin-top: 20px;
        line-height: 28px;
        color: var(--el-menu-text-color);
        font-size: 13px;
      }

      .text-red {
        font-size: 24px;
        color: red;
      }

      .item-right {
        margin-right: 14px;
      }

      .red {
        color: var(--el-color-danger)
      }

      .green {
        color: var(--el-color-success);
      }
    }

    :deep(.el-table--border::before),
    :deep(.el-table--border::after),
    :deep(.el-table__inner-wrapper::before),
    :deep(.el-table__border-left-patch) {
      display: none;
    }

    :deep(.el-table--border .el-table__inner-wrapper tr:first-child th:first-child),
    :deep(.el-table--border .el-table__inner-wrapper tr:first-child td:first-child) {
      border-left: none !important;
    }

    :deep(.el-table--border .el-table__cell:last-child) {
      border-right: none;
    }

    :deep(.el-table__row) {
      &:last-child {
        .el-table__cell {
          border-bottom: none;
        }
      }
    }
  }

  .table-box {
    background: #fff;
    margin-top: 10px;

    :deep(.el-table__header-wrapper .el-table__cell) {
      background: var(--el-color-primary-light-9);
      color: var(--next-bg-menuBar-light-1);
    }

    :deep(thead .cell) {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(thead .el-icon) {
      margin-top: -2px;
      cursor: pointer;
    }

    .primary {
      cursor: pointer;
      color: var(--el-color-primary);
    }

    .short {
      display: block;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}
</style>
